﻿using System.Collections.Generic;
using System.Linq;
using ETModel;

namespace ETHotfix {
    [ObjectSystem]
    public class UnitsComponentSystem : AwakeSystem<UnitsComponent> {
        public override void Awake(UnitsComponent self) {
            self.Awake();
        }
    }

    /// <summary>
    /// 单位管理组件,框架默认加载到场景对象
    /// </summary>
    public class UnitsComponent : Component {

        private readonly Dictionary<long, Unit> idUnits = new Dictionary<long, Unit>();

        public void Awake() {
        }

        public override void Dispose() {
            if (this.IsDisposed) {
                return;
            }
            base.Dispose();

            foreach (Unit unit in this.idUnits.Values) {
                unit.Dispose();
            }

            this.idUnits.Clear();
        }

        public void Add(Unit unit) {
            this.idUnits.Add(unit.Id, unit);
            unit.Parent = this;
        }

        public Unit Get(long id) {
            Unit unit;
            this.idUnits.TryGetValue(id, out unit);
            return unit;
        }

        public void Remove(long id) {
            Unit unit;
            this.idUnits.TryGetValue(id, out unit);
            this.idUnits.Remove(id);
            unit?.Dispose();
        }

        public void RemoveNoDispose(long id) {
            this.idUnits.Remove(id);
        }

        public int Count {
            get {
                return this.idUnits.Count;
            }
        }

        public Unit[] GetAll() {
            return this.idUnits.Values.ToArray();
        }
    }
}